//
//  SSOrderTimeSelectController.swift
//  hangge_2258
//
//  Created by sky.wei on 2023/4/18.
//  Copyright © 2023 hangge. All rights reserved.
//

import UIKit
import SwiftyJSON


public typealias SSOrderTimeClosure = (_ date: String, _ timeSection:String)->()


class SSOrderTimeSelectController: UIViewController {
    

    var resultClosure: SSOrderTimeClosure?     // 闭包

    //左侧表格数据
    var leftTableData = [SSOrderTime]()
    var selectedLeftData = SSOrderTime()
    var selectedLeftIndexPath: IndexPath = IndexPath(row: 0, section: 0)
    var selectedRightIndexPath: IndexPath = IndexPath(row: 0, section: 0)
    var selectedDate = ""
    var selectedTimeSection = ""
    var serviceType = "1"
    
    //选中数据
    var selectedDatas = [SSOrderTime]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        title = "我的排班"
              
        //将表格添加到页面上
        self.view.addSubview(leftTableView)
        self.view.addSubview(rightTableView)
        
        getDataNetwork()
        
        rightNav()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        leftTableView.frame = CGRect(x: 0, y: 0,
                                     width: UIScreen.main.bounds.width/3,
                                     height: self.view.frame.height)
        rightTableView.frame = CGRect(x: UIScreen.main.bounds.width/3, y: 0,
                                      width: UIScreen.main.bounds.width - (UIScreen.main.bounds.width/3),
                                      height: self.view.frame.height)
    }
    
    func rightNav() {
        

        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn .addTarget(self, action: #selector(rightNavAcion), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
 
    @objc func rightNavAcion(){
        submitNetwork()
    }
    
    //左侧表格
    lazy var leftTableView : UITableView = {
        let leftTableView = UITableView()
        leftTableView.delegate = self
        leftTableView.dataSource = self
        leftTableView.rowHeight = 48
        leftTableView.showsVerticalScrollIndicator = false
        leftTableView.separatorColor = UIColor.clear
        leftTableView.register(SSLeftTableViewCell.self,
                               forCellReuseIdentifier: "leftTableViewCell")
        return leftTableView
    }()
    
    //右侧表格
    lazy var rightTableView : UITableView = {
        let rightTableView = UITableView()
        rightTableView.delegate = self
        rightTableView.dataSource = self
        rightTableView.rowHeight = 48
        rightTableView.showsVerticalScrollIndicator = false
        rightTableView.register(SSRightTableViewCell.self,
                                forCellReuseIdentifier: "rightTableViewCell")
        return rightTableView
    }()

    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.dismiss(animated: true)
    }

    @IBAction func closeAction(_ sender: Any) {
        dismiss(animated: true)
    }
    func dataResult(_ finished: @escaping SSOrderTimeClosure) {
        resultClosure = finished
    }
}

extension SSOrderTimeSelectController : UITableViewDataSource, UITableViewDelegate {
    //表格分区数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    //分区下单元格数量
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if leftTableView == tableView {
            return leftTableData.count
        } else {
            return selectedLeftData.listSeat.count
        }
    }
    
    //返回自定义单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
        if leftTableView == tableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "leftTableViewCell",
                                                     for: indexPath) as! SSLeftTableViewCell
            let model = leftTableData[indexPath.row]
            cell.titleLabel.text = model.shiftsDate
            let b = (model.shiftsDate == selectedLeftData.shiftsDate)
            cell.setSelectedStyle(selected: b)
            cell.redPoint.isHidden = !model.isShowRedPoint
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "rightTableViewCell",
                                                     for: indexPath) as! SSRightTableViewCell
            let model = selectedLeftData.listSeat[indexPath.row]
            cell.setData(model)
            return cell
        }
    }
 
    
    //单元格选中时调用
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //点击的是左侧单元格时
        if leftTableView == tableView {
            self.selectedLeftData.iscurrentRow = false
            let model = self.leftTableData[indexPath.row]
            model.iscurrentRow = true
            self.selectedLeftData = model
            self.leftTableView.reloadData()
            self.rightTableView.reloadData()
            
        }else{
            let model = selectedLeftData.listSeat[indexPath.row]
            model.isSeat = !model.isSeat
            var b = false
            for item in selectedLeftData.listSeat {
                if(item.isSeat){
                    b = true
                    break
                }
            }
            self.selectedLeftData.isShowRedPoint = b
            self.rightTableView.reloadData()
            self.leftTableView.reloadData()
        }
    }

}

extension SSOrderTimeSelectController{
    func getDataNetwork() {
        let param = [
                    "phoneNo": kUserPhone
        ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getEMPCleanShift_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    
                    guard let orderTimes = [SSOrderTime].deserialize(from: result, designatedPath:"data.listShift") else {
                        return
                    }
                    
                    for item in orderTimes {
                        var b = false
                        for subItem in item!.listSeat {
                            if(subItem.isSeat){
                                b = true
                            }
                        }
                        item?.isShowRedPoint = b
                    }
                    self.leftTableData = orderTimes as! [SSOrderTime]
                    self.selectedLeftData = self.leftTableData.first ?? SSOrderTime()

                    self.leftTableView.reloadData()
                    self.rightTableView.reloadData()
                }else{
                    dissmissToTast(msg: retMsg)
                }
            }
        }
    }
    
    func submitNetwork() {
        var dic = [
            "phoneNo": kUserPhone
        ] as [String:Any]
        var listSpecs:Array<Any> = []
        for item in self.leftTableData {
            
            if(item.isShowRedPoint){
                for subItem in item.listSeat {
                    if(subItem.isSeat){
                        let spec = [
                            "shiftsDate": item.shiftsDate,
                            "periodType": subItem.periodType,
                        ] as [String : Any]
                        listSpecs.append(spec)
                    }
                }
            }
        }
        dic["listSeat"] = listSpecs
        SSNetwrokManager.share.request(urlString: APIUrl.share.seatCommit_URL,parameters:dic as [String : AnyObject]) { result in
            self.navigationController?.popViewController(animated: true)
            dissmissToTast(msg: "排班时间提交成功")
        }
    }
    
}
